# -*- coding: utf-8 -*-
import json
import decimal
from flask import request, redirect, Flask, jsonify, Response, session
from flask_restful import Resource
from fullstack import app, api, db
from fullstack.Models.member.MemberComments import MemberComments
from fullstack.Models.food.Food import Food
from fullstack.Models.pay.PayOrder import PayOrder
from fullstack.Models.pay.PayOrderItem import PayOrderItem
from fullstack.utils import iPagination, getCurrentTime, MultiEnCoder, paginate, getCurrentDate
from fullstack.utils import getDictFilterField, selectFilterObj, getDictListFilterField
from sqlalchemy import func


class WelcomeData(Resource):
    def get(self):
        resp = {'code': 200, 'value': {}}
        # 商品数目
        food_number = Food.query.count()
        # 待发货数量 express_status=-7
        toSend_number = PayOrder.query.filter_by(express_status=-7).count()
        # 待确认数量 express_status=-6
        toConfirm_number = PayOrder.query.filter_by(express_status=-6).count()
        # 已完成数量 express_status=1, comment_status=1
        finished_number = PayOrder.query.filter_by(
            express_status=1, comment_status=1).count()
        # 已关闭数量 express_status=-8, status=0
        closed_number = PayOrder.query.filter_by(
            express_status=-8, status=0).count()
        # 总销售数量
        total_sale_number = db.session.query(
            func.sum(PayOrderItem.quantity)).filter_by(status=1).scalar()
        # 总库存总量
        # total_stock_number = db.session.query(func.sum(Food.stock)).scalar()
        resp['value'] = {
            'food_number': str(food_number),
            'toSend_number': str(toSend_number),
            'toConfirm_number': str(toConfirm_number),
            'finished_number': str(finished_number),
            'closed_number': str(closed_number),
            'total_sale_number': str(total_sale_number),
            # 'total_stock_number': str(total_stock_number)
        }
        return jsonify(resp)


api.add_resource(WelcomeData, '/vue/api/welcome/data')


class Tests(Resource):
    def get(self):
        comments_model=MemberComments.query.all()
        if comments_model:
            for item in comments_model:
                item_model=PayOrderItem.query.filter_by(pay_order_id=item.pay_order_id,status=1)
                if item_model:
                    for items in item_model:
                        food_model=Food.query.filter_by(id=items.food_id).first()
                        if food_model:
                            food_model.comment_count=food_model.comment_count+1
                            db.session.add(food_model)
                            db.session.commit()
        return jsonify(status=200)


api.add_resource(Tests, '/vue/api/welcome/test')
